/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.generator.repository.adaptor.property;

//import Inspur.Gsp.Caf.Generator.BaseInfoItem.*;
//import Inspur.Gsp.Caf.Generator.FieldGenerator.*;
//import Inspur.Gsp.Caf.Generator.Utils.*;
//import Inspur.Gsp.Cef.Api.Attribute.*;
//import Microsoft.CodeAnalysis.*;
//import Microsoft.CodeAnalysis.CSharp.*;
//import Microsoft.CodeAnalysis.CSharp.Syntax.*;
//import Inspur.Gsp.Cef.Spi.Entity.*;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.caf.generator.baseInfo.TypeInfo;
import com.inspur.edp.caf.generator.field.FieldGenerator;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.GspAssociation;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.cef.generator.repository.RepositoryGenUtil;
import com.inspur.edp.cef.generator.repository.dac.DataTypeDacGenContext;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.udt.designtime.api.entity.ComplexDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.SimpleDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.UnifiedDataTypeDef;
import com.inspur.edp.udt.designtime.api.entity.dbInfo.ColumnMapType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import lombok.var;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.Initializer;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.StringLiteral;

public class DataTypeMappingGenerator extends FieldGenerator {
//	private NestedConfigAtrribute attribute;
	private String propertyName;
	private IGspCommonField gspCommonField;
	private DataTypeDacGenContext dataTypeDacGenContext;
	private UnifiedDataTypeDef udt;
	//private Dictionary<string, string> mapping = new Dictionary<string, string>(){{"a","A"},{"b","B"},{"c","C"}};
	public String getGeneratedName() {
		return getFieldName();
	}

	public DataTypeMappingGenerator(DataTypeDacGenContext dataTypeDacGenContext, IGspCommonField gspCommonField, String propertyName) {
		this.dataTypeDacGenContext = dataTypeDacGenContext;
		this.gspCommonField = gspCommonField;
		this.propertyName = propertyName;
		udt = (UnifiedDataTypeDef)dataTypeDacGenContext.getReposContext().getCefContext().getCefGenContext().getMetadataJitContext().getMetadata(gspCommonField.getUdtID()).getContent();
	}

	@Override
	protected TypeInfo getFieldType()
	{
		TypeInfo typeInfo=new TypeInfo(LinkedHashMap.class);
		addImport(LinkedHashMap.class.getTypeName());
		typeInfo.setIsParameterizedType(true);
		typeInfo.getArguments().add(new TypeInfo(String.class));
		typeInfo.getArguments().add(new TypeInfo(String.class));
		return typeInfo;
	}

	@Override
	protected String getFieldName() {
		return getFieldName(propertyName);
	}

	public static String getFieldName(String propertyName) {
		return String.format("%1$sMapping", propertyName);
	}

	@Override
	protected java.util.ArrayList<Modifier.ModifierKeyword> getAccessModifier() {
		return RepositoryGenUtil.createModifierKeywordArray(Modifier.ModifierKeyword.PRIVATE_KEYWORD);
	}

	@Override
	protected Expression buildGetMethodBody() {
		ClassInstanceCreation classInstanceCreation = ast.newClassInstanceCreation();

//		TypeInfo hashMapType = RepositoryGenUtil.getHashMapTypeInfo(ast, String.class, String.class);
		classInstanceCreation.setType(ast.newSimpleType(ast.newName(LinkedHashMap.class.getTypeName())));

		AnonymousClassDeclaration anonymousClassDeclaration = ast.newAnonymousClassDeclaration();
		Initializer initializer = ast.newInitializer();
		Block block = ast.newBlock();
		block.statements().addAll(getMappingValues());
		initializer.setBody(block);
		anonymousClassDeclaration.bodyDeclarations().add(initializer);
		classInstanceCreation.setAnonymousClassDeclaration(anonymousClassDeclaration);

		return classInstanceCreation;
	}

	private SimpleDataTypeDef getSimpleUdt(){
		return (SimpleDataTypeDef)udt;
	}

	private java.util.ArrayList<Statement> getMappingValues() {
		java.util.ArrayList<Statement> keValuePairs = new java.util.ArrayList<Statement>();
		if(udt instanceof  SimpleDataTypeDef){
			udt = (SimpleDataTypeDef)udt;
			switch (getSimpleUdt().getObjectType()) {
				case None:
					keValuePairs.add(getExpress(gspCommonField.getLabelID(), getSimpleUdt().getCode()));
					break;
				case Association:
					addAssUdtMapping(keValuePairs, getSimpleUdt().getCode());
					break;
				case Enum:
					keValuePairs.add(getExpress(gspCommonField.getLabelID(), getSimpleUdt().getCode()));
					break;
				default:
					break;
			}
		}
		else if(udt instanceof ComplexDataTypeDef){
			if(((ComplexDataTypeDef)udt).getDbInfo().getMappingType() == ColumnMapType.SingleColumn){
				keValuePairs.add(getExpress(gspCommonField.getLabelID(), udt.getCode()));
			}
			else if(((ComplexDataTypeDef)udt).getDbInfo().getMappingType() == ColumnMapType.MultiColumns){

				for(IGspCommonField child: this.gspCommonField.getChildElements()){
					IGspCommonField refUdtField = null;
					for(IGspCommonField udtField: udt.getContainElements()){
						if(this.gspCommonField.getMappingRelation().getMappingInfo(child.getID()).equals(udtField.getID())){
							refUdtField = udtField;
							break;
						}
					}
					keValuePairs.add(getExpress(child.getLabelID(), refUdtField.getLabelID()));
				}
			}
		}
		return keValuePairs;
	}

	private ExpressionStatement getExpress(String key, String value){
		ArrayList arguments = new ArrayList();
		StringLiteral arg1 = RepositoryGenUtil.createStringLiteral(ast, key);
		StringLiteral arg2 = RepositoryGenUtil.createStringLiteral(ast, value);
		arguments.add(arg2);
		arguments.add(arg1);
		MethodInvocation methodInvocation = RepositoryGenUtil.createMethodInvocation(ast, null, "put", arguments);
		ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
		return expressionStatement;
	}

	private void addAssUdtMapping(ArrayList<Statement> keValuePairs, String udtCode) {

		var fieldAssociation = gspCommonField.getChildAssociations().get(0);

		var udtAssociation = getSimpleUdt().getChildAssociations().get(0);
		keValuePairs.add(getExpress(gspCommonField.getLabelID(), udt.getCode()));

		for (var item : fieldAssociation.getRefElementCollection()) {
			if (!item.getIsFromAssoUdt()) {
				continue;
			}
			IGspCommonField udtRefField =
					getElementByRefElementID(udtAssociation, item.getRefElementId(), item.getLabelID());
			keValuePairs.add(getExpress(item.getLabelID(), udtRefField.getLabelID()));
			if(udtRefField.getObjectType() == GspElementObjectType.Association || udtRefField.getIsFromAssoUdt()){
				getMappingValues(item.getLabelID(), udtCode, udtRefField, keValuePairs, fieldAssociation.getRefModelID());
			}
		}
	}

	private void getMappingValues(String prefix1, String udtCode, IGspCommonField commonField, ArrayList<Statement> keValuePairs, String refModelId){
		if(!(commonField.getObjectType() == GspElementObjectType.Association || commonField.getIsUdt()))
			return;
		GspMetadata metadata = this.dataTypeDacGenContext.getReposContext().getCefContext().getCefGenContext().getMetadataJitContext().
				getMetadata(refModelId);
		if(metadata.getContent() instanceof GspBusinessEntity){
			GspBusinessEntity gspBusinessEntity = (GspBusinessEntity) metadata.getContent();
			IGspCommonField gspCommonField = gspBusinessEntity.findElementById(commonField.getRefElementId());
			if(gspCommonField.getObjectType() == GspElementObjectType.Association){
				for(var item : gspCommonField.getChildAssociations().get(0).getRefElementCollection()){
					String preLabel = prefix1.substring(0, prefix1.lastIndexOf("_"));
					keValuePairs.add(getExpress(preLabel + "_" + item.getLabelID(), udtCode+ "_" + item.getLabelID()));
				}
			}
			if(gspCommonField.getChildElements() !=null && gspCommonField.getChildElements().size() > 0){//关联多值udt
				for(var item : gspCommonField.getChildAssociations().get(0).getRefElementCollection()){
					String preLabel = prefix1.substring(0, prefix1.lastIndexOf("_"));
					keValuePairs.add(getExpress(preLabel + "_" + item.getLabelID(), item.getLabelID()));
				}
			}
		}
	}

	private IGspCommonField getElementByRefElementID(
			GspAssociation udtAssociation, String refElementID, String labelId) {

		for (var item : udtAssociation.getRefElementCollection()) {
			if (refElementID.equals(item.getRefElementId())) {
				return item;
			}
		}
		throw new RuntimeException(
				"找不到UDT[" + udt.getCode() + "]关联字段" + refElementID + "----" + labelId);
	}
}
